package com.dtb.trade.controller;

import com.alibaba.fastjson.JSONObject;
import com.dtb.trade.entity.Block;
import com.dtb.trade.entity.PointDeal;
import com.dtb.trade.util.RedisService;
import com.dtb.trade.service.TradeService;
import com.dtb.trade.util.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:ChengJian
 * @Description:
 * @Date: Created in 下午5:26 2018/8/9
 */
@Controller
@Slf4j
public class TradeController {


    @Autowired
    TradeService tradeService;

    @Autowired
    RedisService redisService;


    //查询区块地址
    @GetMapping(value = "/block/{id}")
    public String getBlockAdress(@PathVariable("id")String id, ModelMap modelMap){
        //获取所有区
        List<Block> list = tradeService.getAllBlock();
        int userId  = Integer.valueOf(id);
        if (list == null){
            modelMap.put("msg","区块信息为空");
            modelMap.put("success",false);
            modelMap.put("code",210);
        }

        List<PointDeal> results = new ArrayList<>();
        for (Block block:list){
            List<PointDeal> pointDeals = JSONObject.parseArray(block.getData(),PointDeal.class);
            List<PointDeal> list1 = pointDeals.stream().filter(pointDeal -> pointDeal.getBuyUserId().equals(userId)).collect(Collectors.toList());
            if (pointDeals != null){
                results.addAll(list1);
            }
        }

        modelMap.put("page",results);
        return "/blockInfo";

    }


    //测试记账
    @GetMapping(value = "/block/test")
    public void test1(){
        List<PointDeal> list = tradeService.gainAllTrade();

        if (list.size()>0){
            //获取交易块
            Block block = null;
            String index = redisService.get("blockIndex");
            if (StringUtils.isEmpty(index)){
                //直接从数据库查询
                boolean isHave = tradeService.isBlock();
                if (!isHave){
                    //生成创世区块
                    tradeService.hyperledgerTwo(firstBlock(),list);
                }
                block = tradeService.getNewBlock();
                tradeService.hyperledger(block,list);

            }else {
                //查询区块信息
                block = tradeService.selectBlock(Integer.valueOf(index));
                if (block != null){
                    tradeService.hyperledger(block,list);
                }else {
                    System.out.println("区块出现异常");
                }
            }
        }

    }


    public static Block firstBlock(){

        Block block = new Block();

        String prev = "0000000000000000000000000000000000000000000000000000000000000000";
        int index   = 1;
        int nonce   = 1;
        long time   = System.currentTimeMillis();
        String hash = EncryptUtil.Encrypt(prev+index+nonce+time);
        List<PointDeal> list = new ArrayList<>();


        block.setPreviousHash(prev);
        block.setIndex(index);
        block.setNonce(nonce);
        block.setHash(hash);
        block.setTimestamp(time);
        block.setPointDeals(null);
        block.setPointDeals(list);

        return block;
    }
}
